<template>
  <div class="pagination">
    <button @click="changePageNum(pageNo-1)" :disable="pageNo===1">上一页</button>
    <button  @click="changePageNum(1)" v-show="startAndEnd.start> 1">1</button>
    <span v-show="startAndEnd.start > 2">...</span>
    <button @click="changePageNum( index + startAndEnd.start)" v-for="(_,index) in (startAndEnd.end - startAndEnd.start + 1)" :key="_" 
    :class="{active: index + startAndEnd.start == pageNo}"
    
    > {{index + startAndEnd.start}} </button>
    <button v-show="startAndEnd.end < totalPage - 1">···</button>
    <button @click="changePageNum(totalPage)"  v-show="startAndEnd.end < totalPage"> {{totalPage}} </button>
    <button @click="changePageNum(pageNo + 1)"  :disable="pageNo===totalPage">下一页</button>

    <span>共 {{total}} 条</span>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["total", "pageSize", "continues", "pageNo"],
  computed: {
    // 计算总页码数
    totalPage() {
      const { total, pageSize } = this;
      return Math.ceil(total / pageSize);
    },
    // 计算起始结束页
    startAndEnd() {
      const { pageNo, continues, totalPage } = this;
      let start, end;
      // 如果连续页数大于了总页数的情况 也就是没有那么多的连续页
      if (continues > totalPage) {
        start = 1;
        end = totalPage;
      } else {
        start = pageNo - parseInt(continues / 2);
        end = pageNo + parseInt(continues / 2);
      }
      // 如果起始页小于了1
      if(start < 1) {
        start = 1
        end = continues
      }
       // 如果结束页大于了总页码  
       if(end > totalPage) {
        start = totalPage - continues + 1 // 开始页要从后往前算
        end = totalPage
       }
      return { start, end };
    },
  },
  methods:{
    // 单击按钮，实现分页
    changePageNum(pageNum) {
      this.$emit('get-pageNo',pageNum)
    }
  }
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }
  span {
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>